# 管理员对商品分类进行管理，还可以进行其他管理操作

from flask import Blueprint,render_template,request,flash,redirect,url_for
from app.models import Category,db
from flask_login import login_required,current_user

bp = Blueprint('admin',__name__,url_prefix='/admin')

# before_request--->在请求之前进行拦截检查
@bp.before_request
@login_required
def check_admin():
    if not current_user.is_admin:
        flash('非管理员用户，滚犊子...')
        return redirect(url_for('index.index'))

# 查询所有商品分类
@bp.route('/categories')
def categories():
    categories = Category.query.all()
    return render_template('admin_categories.html',categories=categories)

# 添加商品分类
@bp.route('/categories/add',methods=['POST'])
def add_category():
    name=request.form.get('name')
    if name:
        category = Category(name=name)
        db.session.add(category)
        db.session.commit()
        flash('分类添加成功')
    return redirect(url_for('admin.categories'))


# 删除分类
@bp.route('/categories/delete/<int:category_id>',methods=['GET','POST'])
def delete_category(category_id):
    category=Category.query.get_or_404(category_id)
    # 将查询出的分类进行删除
    db.session.delete(category)
    db.session.commit()
    flash('分类删除成功')
    return redirect(url_for('admin.categories'))